package postgres

import (
	log "auth/collector/logger"
	"github.com/casbin/casbin/v2"
	"github.com/casbin/casbin/v2/model"
	gormadapter "github.com/casbin/gorm-adapter/v3"
)

type casbinService struct {
}

var CasbinService = &casbinService{}

func (a *casbinService) Casbin() (*casbin.CachedEnforcer, error) {
	var (
		cachedEnforcer *casbin.CachedEnforcer
	)
	d, err := gormadapter.NewAdapterByDB(db)
	if err != nil {
		log.Error("适配数据库失败", err)
		return nil, err
	}
	text := `
		[request_definition]
		r = sub, obj, act
		
		[policy_definition]
		p = sub, obj, act
		
		[role_definition]
		g = _, _
		
		[policy_effect]
		e = some(where (p.eft == allow))
		
		[matchers]
		m = r.sub == p.sub && keyMatch2(r.obj,p.obj) && r.act == p.act
		`
	m, err := model.NewModelFromString(text)
	if err != nil {
		log.Error("字符串加载模型失败!", err)
		return nil, err
	}
	cachedEnforcer, _ = casbin.NewCachedEnforcer(m, d)
	cachedEnforcer.SetExpireTime(60 * 60)
	_ = cachedEnforcer.LoadPolicy()
	return cachedEnforcer, err
}

func (a *casbinService) UpdateCasbinApi(oldPath string, newPath string, oldMethod string, newMethod string) error {
	err := db.Model(&gormadapter.CasbinRule{}).Where("v1 = ? AND v2 = ?", oldPath, oldMethod).
		Updates(map[string]interface{}{
			"v1": newPath,
			"v2": newMethod,
		}).Error
	return err
}
